<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="单据编号"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billNo"
            >
              <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="审批流程"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="task"
            >
              <a-input v-model="model.task" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="单据日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="billDate"
            >
              <j-date
                placeholder="请选择日期"
                v-model="model.billDate"
                style="width: 100%"
                :disabled="formDisabled"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="发件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseBy"
            >
              <a-input v-model="model.purchaseBy" placeholder="请输入发件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="需方单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseCompany"
            >
              <a-input v-model="model.purchaseCompany" placeholder="请输入需方单位"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="purchaseFixPhone"
            >
              <a-input v-model="model.purchaseFixPhone" placeholder="请输入电话"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="供方单位"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierName"
            >
              <!-- <tsl-supplier
                v-model="model.supplierName"
                :isDisabled="formDisabled"
                @handlerOk="onSelectSupplier"
              ></tsl-supplier>-->
              <select-supplier-single
                v-model="model.supplierName"
                :isDisabled="formDisabled"
                @onSuppliersSelected="onSelectSupplier"
              ></select-supplier-single>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="收件人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierBy"
            >
              <a-input v-model="model.supplierBy" placeholder="请输入收件人"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="传真电话"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="supplierPhone"
            >
              <a-input v-model="model.supplierPhone" placeholder="请输入传真电话"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="交货地点"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="arrivalPlace"
            >
              <a-input v-model="model.arrivalPlace" placeholder="请输入交货地点"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="总金额"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="money"
            >
              <a-input v-model="model.money"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="总金额大写"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="moneyUpper"
            >
              <a-input v-model="model.moneyUpper"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item
              label="制单人"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createBy"
            >
              <a-input v-model="model.createBy" placeholder="请输入申请人" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单部门"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="sysOrgCode"
            >
              <j-select-depart disabled v-model="model.sysOrgCode" :multi="false" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="制单日期"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="createTime"
            >
              <a-input v-model="model.createTime" disabled></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-card title="供方信息">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="供方单位"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierName"
                  >
                    <a-input v-model="model.supplierName"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="地址"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierAddress"
                  >
                    <a-input v-model="model.supplierAddress"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="委托人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierBy"
                  >
                    <a-input v-model="model.supplierBy"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="电话"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierPhone"
                  >
                    <a-input v-model="model.supplierPhone"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="税号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierTax"
                  >
                    <a-input v-model="model.supplierTax"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="开户银行"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierBank"
                  >
                    <a-input v-model="model.supplierBank"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="账号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierAccount"
                  >
                    <a-input v-model="model.supplierAccount"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="邮编"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="supplierMail"
                  >
                    <a-input v-model="model.supplierMail"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card title="需方信息">
              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="需方单位"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseCompany"
                  >
                    <a-input v-model="model.purchaseCompany"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="地址"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseAddress"
                  >
                    <a-input v-model="model.purchaseAddress"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="委托人"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseBy"
                  >
                    <a-input v-model="model.purchaseBy"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="电话"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchasePhone"
                  >
                    <a-input v-model="model.purchasePhone"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="税号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseTax"
                  >
                    <a-input v-model="model.purchaseTax"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="开户银行"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseBank"
                  >
                    <a-input v-model="model.purchaseBank"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>

              <a-row>
                <a-col :span="12">
                  <a-form-model-item
                    label="账号"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseAccount"
                  >
                    <a-input v-model="model.purchaseAccount"></a-input>
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <a-form-model-item
                    label="邮编"
                    :labelCol="labelCol"
                    :wrapperCol="wrapperCol"
                    prop="purchaseMail"
                  >
                    <a-input v-model="model.purchaseMail"></a-input>
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-card>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
    <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="明细" :key="refKeys[0]" :forceRender="true">
        <a-row justify="start">
          <!-- 新增 -->
          <a-col :span="12">
            <a-space>
              <a-button
                type="primary"
                icon="PlusCircleOutlined"
                size="default"
                @click="addExtraApplicationBill"
                v-show="!formDisabled"
              >追加</a-button>
            </a-space>
          </a-col>
          <a-col :span="12"></a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <j-vxe-table
              keep-source
              :ref="refKeys[0]"
              :loading="sparePartPurchaseBillDetailTable.loading"
              :columns="sparePartPurchaseBillDetailTable.columns"
              :dataSource="sparePartPurchaseBillDetailTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="false"
              :rowSelection="true"
              class="j-table-force-nowrap1"
              :clickSelectRow="true"
              rowSelectionType="radio"
              @edit-closed="editClosedEvent"
            >
              <template v-slot:action="props">
                <a-popconfirm
                  v-show="!formDisabled"
                  title="确定删除吗？"
                  @confirm="handleDelDetail(props)"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </j-vxe-table>
          </a-col>
        </a-row>
      </a-tab-pane>
    </a-tabs>

    <select-spare-part-application-list-modal
      ref="applicationList"
      @selectBill="handleSelect"
      title="追加请购单"
      :checkval="checkType"
    ></select-spare-part-application-list-modal>
  </a-spin>
</template>

<script>
import { getAction, httpAction, postAction, putAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { getRefPromise, VALIDATE_FAILED } from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import store from '@/store'
import moment from 'dayjs'
import TslSupplier from '@comp/tsl/TslSupplier.vue'
import JSelectDepart from '@/components/jeecgbiz/JSelectDepart'
import SelectSparePartApplicationListModal from './SelectSparePartApplicationListModal'
import { dealBigMoney } from '@/utils/util'
import SelectSupplierSingle from '@comp/base/SelectSupplierSingle'
import { definitionStartByDataId, isFirstInitiator } from '@views/flowable/api/definition'

export default {
  name: 'SparePartPurchaseBillForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer,
    JSelectDepart,
    TslSupplier,
    SelectSparePartApplicationListModal,
    SelectSupplierSingle,
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      model: {
        billNo: '',
        billDate: '',
        purchaseCompany: '采购部',
        purchaseBy: '于吉伟',
        purchasePhone: '18753506316',
        purchaseFixPhone: '0535-8913889',
        purchaseAddress: '山东省龙口市北马镇北马南路',
        purchaseTax: '37068161345110',
        purchaseBank: '中国银行龙口开发区支行',
        purchaseAccount: '226003071547',
        purchaseMail: '265702',
        allPrice: '',
        task: '五金材料采购订单',
        sparePartPurchaseBillDetailList: [],
        supplierName: '',
      },
      checkType: 'radio',
      supplier: {},
      // 新增时子表默认添加几行空数据
      addDefaultRowNum: 1,
      validatorRules: {
        supplierName: [{ required: true, message: '请输入供方单位!' }],
        billNo: [{ required: true, message: '请输入单据编号!' }],
      },
      refKeys: ['sparePartPurchaseBillDetail'],
      tableKeys: ['sparePartPurchaseBillDetail'],
      activeKey: 'sparePartPurchaseBillDetail',
      // 五金配件订单子表
      sparePartPurchaseBillDetailTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '序号',
            key: 'seq',
            type: JVXETypes.normal,
            width: '80px',
            placeholder: '请输入${title}',
          },
          {
            title: '使用部门',
            key: 'applyDepart',
            type: JVXETypes.normal,
            //width: '100px',
            placeholder: '请输入${title}',
          },
          {
            title: '物料编号',
            key: 'materialNo',
            type: JVXETypes.normal,
            //width: '100px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '物料名称',
            key: 'materialName',
            type: JVXETypes.normal,
            //width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '物料描述',
            key: 'materialDesc',
            type: JVXETypes.input,
            //width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '规格',
            key: 'spec',
            type: JVXETypes.normal,
            //width: '60px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '单位',
            key: 'unit',
            type: JVXETypes.normal,
            width: '60px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          // {
          //   title: '请购单号',
          //   key: 'applyBillNo',
          //   type: JVXETypes.input,
          //   width: '200px',
          //   placeholder: '请输入${title}',
          //   defaultValue: '',
          // },
          {
            title: '采购数量',
            key: 'applyNum',
            type: JVXETypes.normal,
            //width: '80px',
            defaultValue: '',
          },
          {
            title: '已生成订单数量',
            key: 'generateNum',
            type: JVXETypes.normal,
            //width: '100px',
            defaultValue: '',
          },
          {
            title: '剩余数量',
            key: 'leftNum',
            type: JVXETypes.normal,
            //width: '80px',
            defaultValue: '',
          },
          {
            title: '数量',
            key: 'num',
            type: JVXETypes.input,
            //width: '80px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '单价',
            key: 'price',
            type: JVXETypes.input,
            //width: '80px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '金额',
            key: 'money',
            type: JVXETypes.normal,
            //width: '100px',
            placeholder: '请输入${title}',
            validateRules: [
              {
                required: true, // 必填
                message: '请输入${title}', // 显示的文本
              },
            ],
          },
          {
            title: '要求到货日期',
            key: 'arrivalDate',
            type: JVXETypes.datetime,
            width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '联系方式',
            key: 'hone',
            type: JVXETypes.input,
            //width: '100px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.input,
            //width: '150px',
            placeholder: '请输入${title}',
            defaultValue: '',
          },
          {
            title: '操作',
            key: 'action',
            type: JVXETypes.slot,
            fixed: 'right',
            minWidth: '100px',
            align: 'center',
            slotName: 'action',
          },
        ],
      },
      url: {
        add: '/procurement/sparePartPurchaseBill/add',
        edit: '/procurement/sparePartPurchaseBill/edit',
        queryById: '/procurement/sparePartPurchaseBill/queryById',
        sparePartPurchaseBillDetail: {
          list: '/procurement/sparePartPurchaseBill/querySparePartPurchaseBillDetailByMainId',
        },
      },
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
    customFormData: {
      type: Object,
      default: () => {
        return {}
      },
      required: false,
    },
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss')
    this.model.billDate = moment().format('YYYY-MM-DD')
    let user = store.getters.userInfo
    if (!this.model.createBy) {
      this.model.createBy = user.username
      this.model.sysOrgCode = user.departIds
    }

    //如果是审批流进来的时候要将审批流的数据显示出来
    if (this.customFormData.id != null) {
      this.model = this.customFormData
      //刷新子表数据
      this.editAfter()
    }
  },
  methods: {
    generateBillNo() {
      let url = '/sys/fillRule/executeRuleByCode/spare_part_purchase_bill'
      putAction(url, {}).then((res) => {
        // 执行成功，获取返回的值，并赋到页面上
        if (res.success) {
          this.model.billNo = res.result
        }
      })
    },
    addBefore() {
      this.sparePartPurchaseBillDetailTable.dataSource = []
    },
    add() {
      this.generateBillNo()
      //这里单位字段获取不到怎么解决
      this.sparePartPurchaseBillDetailTable.dataSource = []

      let tempList = store.getters.selectApplicationDetail
      if (tempList.length > 0) {
        let sumNum = 0
        tempList.forEach((row, index) => {
          this.sparePartPurchaseBillDetailTable.dataSource.push({
            applyBillDetailId: row.detailId,
            applyBillNo: row.billNo,
            materialId: row.materialId,
            materialNo: row.materialNo,
            materialName: row.materialName,
            materialDesc: row.materialDesc,
            spec: row.spec,
            num: row.unPurchaseNum,
            arrivalDate: row.arriveDate,
            unit: row.unit,
            price: row.price,
            applyNum: row.num,
            generateNum: row.purchaseNum,
            leftNum: row.unPurchaseNum,
            applyBillNo: row.billNo,
            applyDepart: row.applyDepart,
            remark: row.remark,
            seq: index + 1,
            money: row.unPurchaseNum && row.price ? (row.unPurchaseNum * row.price).toFixed(2) : 0,
          })

          if (row.unPurchaseNum && row.price) {
            sumNum += row.unPurchaseNum * row.price
          }
        })

        this.model.money = sumNum.toFixed(2)
        if (this.model.money) {
          this.model.moneyUpper = dealBigMoney(this.model.money)
        }

        //只有有供应商才加载供应商信息
        if (tempList[0].supplierNo) {
          this.showSupplierInfo(tempList[0].supplierNo)
        }
      }
    },
    showSupplierInfo(supplierNo) {
      // 加载供应商信息
      getAction('/base/erpSupplier/list', { code: supplierNo }).then((res) => {
        if (res.result && res.result.records && res.result.records.length > 0) {
          this.supplier = res.result.records[0]
          this.model.supplierId = this.supplier.id
          this.model.supplierNo = this.supplier.code
          this.model.supplierName = this.supplier.name
          this.model.supplierAddress = this.supplier.address
          this.model.supplierBy = this.supplier.contact
          this.model.supplierPhone = this.supplier.telephone
          this.model.supplierTax = this.supplier.agent
          this.model.supplierAccount = this.supplier.accountNo
          this.model.supplierBank = this.supplier.bankName
          this.model.supplierMail = this.supplier.email
          this.$forceUpdate()
        }
      })
    },
    getAllTable() {
      let values = this.tableKeys.map((key) => getRefPromise(this, key))
      return Promise.all(values)
    },
    /** 调用完edit()方法之后会自动调用此方法 */
    editAfter() {
      this.$nextTick(() => {})
      // 加载子表数据
      if (this.model.id) {
        this.model.task = '五金材料采购订单'

        let params = { id: this.model.id }
        this.requestSubTableData(
          this.url.sparePartPurchaseBillDetail.list,
          params,
          this.sparePartPurchaseBillDetailTable,
          this.successDetailTable
        )
      }
    },
    //重新加载页面的时候 总金额需要重新计算
    successDetailTable(res) {
      if (
        this.sparePartPurchaseBillDetailTable.dataSource &&
        this.sparePartPurchaseBillDetailTable.dataSource.length > 0
      ) {
        let arr = this.sparePartPurchaseBillDetailTable.dataSource
        let price = 0
        arr.forEach((element) => {
          if (element.num && element.price) {
            price += element.num * element.price
          }
        })

        if (price > 0) {
          this.model.money = price
          this.model.moneyUpper = dealBigMoney(this.model.money)
        }
      }
    },
    //校验所有一对一子表表单
    validateSubForm(allValues) {
      return new Promise((resolve, reject) => {
        Promise.all([])
          .then(() => {
            resolve(allValues)
          })
          .catch((e) => {
            if (e.error === VALIDATE_FAILED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
      })
    },
    /** 整理成formData */
    classifyIntoFormData(allValues) {
      let main = Object.assign(this.model, allValues.formValue)
      return {
        ...main, // 展开
        sparePartPurchaseBillDetailList: allValues.tablesValue[0].tableData,
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    onSelectSupplier(record) {
      this.model.supplierName = record.name
      this.model.supplierId = record.id
      this.model.supplierNo = record.code
      this.model.supplierAddress = record.address
      this.model.supplierBy = record.contact
      this.model.supplierPhone = record.telephone
      this.model.supplierTax = record.fax
      this.model.supplierMail = record.email
      this.model.supplierBank = record.bankName
      this.model.supplierAccount = record.accountNo
      this.model.supplierMail = record.zipCode
      this.$forceUpdate()
    },
    handleSelect(record) {
      if (!record) {
        return
      }

      if (
        this.sparePartPurchaseBillDetailTable.dataSource &&
        this.sparePartPurchaseBillDetailTable.dataSource.length > 0
      ) {
        let item = this.sparePartPurchaseBillDetailTable.dataSource.find(
          (item) => item.applyBillDetailId === record.detailId
        )
        if (item) {
          this.$message.warning('该请购单明细已选择！')
          return
        }
      }

      let detail = {}
      detail.materialName = record.materialName
      detail.materialNo = record.materialNo
      detail.materialId = record.materialId
      detail.materialDesc = record.materialDesc
      detail.applyBillNo = record.billNo
      detail.num = record.unPurchaseNum
      detail.procurementArrayPrice = 0
      detail.spec = record.spec
      detail.unit = record.unit
      detail.applyBillDetailId = record.detailId
      detail.supplierId = record.supplierId
      detail.arrivalDate = record.arrivalDate
      detail.planNum = record.num
      detail.price = record.price
      detail.applyNum = record.num
      detail.generateNum = record.purchaseNum
      detail.leftNum = record.unPurchaseNum
      detail.applyDepart = record.applyDepart
      detail.remark = record.remark
      detail.seq = this.sparePartPurchaseBillDetailTable.dataSource.length + 1

      this.model.sparePartPurchaseBillDetailList.push(detail)
      this.sparePartPurchaseBillDetailTable.dataSource.push(detail)
      if (this.sparePartPurchaseBillDetailTable.dataSource.length > 0) {
        this.showSupplierInfo(this.model.sparePartPurchaseBillDetailList[0].supplierNo)
      }
    },
    addExtraApplicationBill() {
      //追加选择采购计划
      this.$nextTick(() => {
        this.$refs.applicationList.add()
      })
    },
    editClosedEvent({ row, column, cellValue }) {
      if (column.property === 'num' || column.property === 'price') {
        //如果输入数量或者价格时自动计算总价格
        if (row.num && row.price) {
          row.money = (row.num * row.price).toFixed(2)
        }
        if (
          this.sparePartPurchaseBillDetailTable.dataSource &&
          this.sparePartPurchaseBillDetailTable.dataSource.length > 0
        ) {
          let arr = this.sparePartPurchaseBillDetailTable.dataSource
          let price = 0
          let counts = 0
          arr.forEach((element) => {
            if (element.num) {
              counts += element.num
            }
            if (element.num && element.price) {
              price += element.num * element.price
            }
          })

          if (price > 0) {
            this.model.money = price.toFixed(2)
            if (this.model.money) {
              this.model.moneyUpper = dealBigMoney(this.model.money)
            }
            this.$forceUpdate()
          }
        }
      }
    },
    handleDelDetail(props) {
      props.target.removeRows(props.row)
      if (this.sparePartPurchaseBillDetailTable.dataSource.length > 0) {
        this.sparePartPurchaseBillDetailTable.dataSource.splice(
          this.sparePartPurchaseBillDetailTable.dataSource.findIndex((d) => d.id === props.row.id),
          1
        )

        this.sparePartPurchaseBillDetailTable.dataSource.forEach((element, index) => {
          element.seq = index + 1
        })
      }
    },
    //提交表单数据
    request(formData) {
      let url = this.url.add,
        method = 'post'
      if (this.model.id) {
        url = this.url.edit
        method = 'put'
      }
      this.confirmLoading = true

      httpAction(url, formData, method)
        .then((res) => {
          if (res.success) {
            //241119修改提交时还要判断是否直接进入审批流
            if (!this.model.id) {
              this.model.dataId = res.message
              this.applySubmit(this.model)
            }
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    applySubmit(record) {
      if (record.dataId && record.dataId.length < 1) {
        this.$message.error('审批时必须传入参数dataId')
        return
      }

      //对于自定义业务，判断是否是驳回或退回的第一个发起人节点
      isFirstInitiator(record.dataId, record).then((res) => {
        if (res.success && res.result) {
          // 只有第一次能自动申请
          return
        } else {
          var params = Object.assign(
            {
              dataId: record.dataId,
            },
            record
          )
          definitionStartByDataId(record.dataId, 'sparePartPurchaseBillService', params)
            .then((res) => {
              if (res.success) {
                this.$message.success(res.message)
              } else {
                this.$message.error(res.message)
              }
            })
            .finally()
        }
      })
    },
  },
}
</script>

<style scoped></style>
